import { JsonAsset } from "cc";
import { ResourceManager } from "./ResourceManager";
import { readData } from "./uitils";

export const MAP_CELL_SIZE = {
    tileWidth: 1024,
    tileHeight: 1024,
};

export const MAP_CELL_NUM = {
    tileRow: 3,
    tileColno: 6,
};

export enum TERRIAN_TYPE {
    BLANK = 1,
    MINE,
    ROCK,
    FARM,
    WATER,
    WASTE,
    SOUL,
}

export enum BUILD_TYPE {
    FARM = 1,
    IRON,
    FORG,
    FOREST,
    STONM,
    CRYSTAL,
    CEMETERY,
    ALTAR,
}

export interface CityInfoData {
    [proKey: string]: {
        proKey: string;
        proVal: string | number;
        speed: number;
        limit: number;
    };
}

class MapData {
    bgBlockList: { [blockId: string]: string } = {};
    terrianList: { [cityId: string]: { type: number; pos: string } } = {};
    terrianLines: { [lineName: string]: { startPos: string; toPos: string; len: number } } = {};

    cityDetails: { [cityId: string]: CityInfoData } = {};
    initMapData = false;
    initCityData = false;

    static _instance: MapData = new MapData();
    constructor() {}

    async loadMapJson(callFunc?: Function) {
        if (this.initMapData) {
            if (callFunc) {
                this.loadCityJson();
                callFunc();
            }
            return;
        }

        const mapData: any = await readData("map", ".json");
        // const mapDataJson: JsonAsset = await ResourceManager.getInstance().loadPath("cfg/map");
        // const mapData: any = mapDataJson.json;
        if (mapData && Object.keys(mapData).length > 0) {
            this.bgBlockList = mapData.bgTile;
            this.terrianList = mapData.terrians;
            this.terrianLines = mapData.lines;
        }
        if (callFunc) {
            this.loadCityJson();
            callFunc();
        }
        this.initMapData = true;
    }

    async loadCityJson() {
        if (this.initCityData) {
            return;
        }
        const cityData: any = await readData("city", ".json");
        // const cityDataJson: JsonAsset = await ResourceManager.getInstance().loadPath("cfg/city");
        // const cityData: any = cityDataJson.json;
        if (cityData && Object.keys(cityData).length > 0) {
            this.cityDetails = cityData;
        }
        this.initCityData = true;
    }

    // 随机获取一个城市
    getRandomCity(): string {
        const cityIds = Object.keys(this.terrianList);
        const cityNum = cityIds.length;
        const randomIdx = Math.floor(Math.random() * cityNum);
        const randomCityId = cityIds[randomIdx];
        return randomCityId;
    }
}

export const mapData = MapData._instance;
